package com.cy.pj.goods.controller;

import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;

@Controller
@RequestMapping("/goods/")//路径映射
public class GoodsController {
    @Autowired
    private GoodsService goodsService;//当前类有一个service接口引用，调用具体的servie类对象方法实现业务逻辑

    @PostMapping("doUpdateGoods")
    public String doUpdateGoods(Goods entity){
        goodsService.updateGoods(entity);
        return "redirect:/goods/doGoodsUI";
    }


    @GetMapping("doFindById/{id}")
    public String doFindById(@PathVariable Integer id,Model model) {
        Goods goods=goodsService.findById(id);
        model.addAttribute("g",goods);
        return "goods-update";
    }

    @PostMapping("doSaveGoods")
    public String doSaveGoods(Goods entity){//用pojo对象接收客户端参数
        goodsService.saveGoods(entity);
        return "redirect:/goods/doGoodsUI";
    }

    @RequestMapping("doGoodsAddUI")
    public String doGoodsAddUI(){
        return "goods-add";
    }

    @RequestMapping("doDeleteById/{id}")//rest风格（软件架构编码风格）url，浏览器，手机，手表，电视
    public String doDeleteById(@PathVariable("id") Integer id){//@PathVariabl描述参数时表示参数的值来自url
        goodsService.deleById(id);
        return "redirect:/goods/doGoodsUI";
    }

    @RequestMapping("doGoodsUI")
    public String doGoodUI(Model model){//Model用来封装响应结果的对象,存储查询数据
        List<Goods> goodsList=goodsService.findGoods();
        model.addAttribute("goodsList",goodsList);
        return "goods";//viewname,返回值会交给DispatcherServlet进行处理，会调ViewResolver
        //解析的过程会在view的名字加上前缀和后缀，同时把model中的数据填充到view上面，结果响应页面（view+model）
    }

}
